import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/video_upload_success_bean.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_folder_detail_event.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_index_event.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_upload_service.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_matisse_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:path_provider/path_provider.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

import '../event/refresh_smart_home_category_event.dart';

class SmartHomePublishService {


  List<SmartHomeUploadItemBean> _uploadList;

  //智能家居门店id
  String _shid;
  BuildContext _context;

  String _scid;
  String _desc;
  int _coverIndex;
  String _title;
  String _sfid;
  String _mid;
  //01 图片 02 视频 03 3D全景
  String _type;
  String _deleteIds;
  ///设置值
  SmartHomePublishService setList(BuildContext context, String shid, String scid, String title,
      String desc,
      List<SmartHomeUploadItemBean> folderList,
      int coverIndex, String sfid, String mid, {String type, String deleteIds}) {
    if (folderList == null || folderList.isEmpty) {
      return null;
    }
    _context = context;
    _uploadList = folderList;
    _shid = shid;
    _scid = scid;
    _desc = desc;
    _coverIndex = coverIndex;
    _title = title;
    _sfid = sfid;
    _mid= mid;
    _type= type;
    _deleteIds = deleteIds;
    return this;
  }

  ///独立上传
  void singleUpload(VgBaseCallback callback)async{
    if (_uploadList == null || _uploadList.isEmpty) {
      callback?.onError("需要上传的数据为空");
      return;
    }
    VgHudUtils.show(_context, "正在发布");
    try {
      for (SmartHomeUploadItemBean item in _uploadList) {
        item = await _manageFolder(item);
      }
    } catch (e) {
      callback?.onError("处理出现异常");
      print("上传报错:$e");
      return;
    }
    _uploadList.removeWhere((element) => element == null);
    List<Future<SmartHomeUploadItemBean>> futureList = List();
    for(int i = 0; i < _uploadList.length; i++){
      SmartHomeUploadItemBean item = _uploadList[i];
      item.sortIndex = i;
      futureList.add(_httpMultiFolder(item, onGetNewFileLength: (value){
        item.folderStorage = value;
      }));
    }
    Future.wait(futureList)
      ..then((List<SmartHomeUploadItemBean> list) {
        list.sort((left, right){
          return left.sortIndex.compareTo(right.sortIndex);
        });
        List<PicListItemBean> picList = new List();
        list.forEach((element) {
          PicListItemBean picListItemBean = new PicListItemBean(
            picurl: element.getPicUrl()??"",
            type: element.type??"",
            picname: element.folderName??"",
            picsize: element.getSize()??"",
            picstorage: element.getStorage()??"",
            scid: element.getScid()??_scid,
            stid: element.getStid()??"",
            style: element.style??"99",
            backup: element.backup??"",
            sysmid: element?.sysmid ?? "",
            picid: element?.picid ?? "",
          );
          picList.add(picListItemBean);
        });
        String picjson = "";
        if(picList.isNotEmpty){
          picjson = json.encode(picList);
        }
        //接口
        String url;
        Map<String, dynamic> paramsMap;
        if(StringUtils.isEmpty(_sfid)){

          url = NetApi.SMART_HOME_PUBLISH_SINGLE_UPLOAD;
          paramsMap = {
            "authId": UserRepository.getInstance().authId ?? "",
            "shid": _shid ?? null,
            "picjson": picjson ?? "",
          };
          print("准备多图上传测试参数: ${paramsMap}");
          VgHttpUtils.post(url,
              params: paramsMap,
              callback: BaseCallback(onSuccess: (val) {
                VgHudUtils.hide(_context);
                callback?.onSuccess(list);
                VgEventBus.global.send(new RefreshSmartHomeCategoryEvent(id: _scid));
                VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
              }, onError: (msg) {
                VgHudUtils.hide(_context);
                callback?.onError(msg);
              }));
        }else{
          url = NetApi.SMART_HOME_EDIT_SINGLE_UPLOAD;
          PicListItemBean itemBean = picList.elementAt(0);
          paramsMap = {
            "authId": UserRepository.getInstance().authId ?? "",
            "backup": itemBean?.backup ?? null,
            "picid": itemBean?.picid ?? null,
            "picsize": itemBean?.picsize ?? null,
            "picstorage": itemBean?.picstorage ?? null,
            "picurl": itemBean?.getCoverUrl() ?? null,
            "scid": itemBean?.scid ?? null,
            "sfid": _sfid ?? null,
            "shid": _shid ?? null,
            "stid": itemBean?.stid ?? null,
            "style": itemBean?.style ?? null,
            "sysmid": itemBean?.sysmid ?? null,
          };
          print("准备多图上传测试参数: ${paramsMap}");
          VgHttpUtils.post(url,
              params: paramsMap,
              callback: BaseCallback(onSuccess: (val) {
                VgHudUtils.hide(_context);
                callback?.onSuccess(list);
                VgEventBus.global.send(new RefreshSmartHomeCategoryEvent(id: _scid));
                VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
                VgEventBus.global.send(new RefreshSmartHomeFolderDetailEvent());
              }, onError: (msg) {
                VgHudUtils.hide(_context);
                callback?.onError(msg);
              }));
        }


      }).catchError((e) {
        VgHudUtils.hide(_context);
        callback?.onError("上传失败");
      });
  }

  ///打包上传
  void packageUpload(VgBaseCallback callback)async{
    if (_uploadList == null || _uploadList.isEmpty) {
      callback?.onError("需要上传的数据为空");
      return;
    }
    VgHudUtils.show(_context, "正在发布");
    try {
      for (SmartHomeUploadItemBean item in _uploadList) {
        item = await _manageFolder(item);
      }
    } catch (e) {
      callback?.onError("处理出现异常");
      print("上传报错:$e");
      return;
    }
    _uploadList.removeWhere((element) => element == null);
    List<Future<SmartHomeUploadItemBean>> futureList = List();
    for(int i = 0; i < _uploadList.length; i++){
      SmartHomeUploadItemBean item = _uploadList[i];
      item.sortIndex = i;
      futureList.add(_httpMultiFolder(item, onGetNewFileLength: (value){
        item.folderStorage = value;
      }));
    }
    Future.wait(futureList)
      ..then((List<SmartHomeUploadItemBean> list) {
        list.sort((left, right){
          return left.sortIndex.compareTo(right.sortIndex);
        });
        List<PicListItemBean> picList = new List();
        list.forEach((element) {
          PicListItemBean picListItemBean = new PicListItemBean(
            picurl: element.getPicUrl()??"",
            type: element.type??"",
            picname: element.folderName??"",
            picsize: element.getSize()??"",
            picstorage: element.getStorage()??"",
            scid: element.getScid()??_scid,
            stid: element.getStid()??"",
            style: element.style??"99",
            backup: element.backup??"",
            sysmid:"",
            picid: element.getPicid(),
          );
          picList.add(picListItemBean);
        });
        String picjson = "";
        if(picList.isNotEmpty){
          picjson = json.encode(picList);
        }
        //接口
        String url;
        Map<String, dynamic> paramsMap;
        if(StringUtils.isEmpty(_sfid)){
          url = NetApi.SMART_HOME_PUBLISH_PACKAGE_UPLOAD;
          paramsMap = {
            "authId": UserRepository.getInstance().authId ?? "",
            "backup": _desc ?? null,
            "coversize": picList.elementAt(_coverIndex)?.picsize ?? null,
            "coverurl": picList.elementAt(_coverIndex)?.getCoverUrl() ?? null,
            "picjson": picjson ?? "",
            "shid": _shid ?? null,
            "scid": _scid ?? "",
            "title": _title ?? null,
            "type": "01",
            "sysmid": _mid ?? "",
          };
          print("准备多图上传测试参数: ${paramsMap}");
          VgHttpUtils.post(url,
              params: paramsMap,
              callback: BaseCallback(onSuccess: (val) {
                VgHudUtils.hide(_context);
                callback?.onSuccess(list);
                VgEventBus.global.send(new RefreshSmartHomeCategoryEvent(id: _scid));
                VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
              }, onError: (msg) {
                VgHudUtils.hide(_context);
                callback?.onError(msg);
              }));
        }else{
          url = NetApi.SMART_HOME_EDIT_PACKAGE_UPLOAD;
          paramsMap = {
            "authId": UserRepository.getInstance().authId ?? "",
            "backup": _desc ?? null,
            "coversize": picList.elementAt(_coverIndex)?.picsize ?? null,
            "coverurl": picList.elementAt(_coverIndex)?.getCoverUrl() ?? null,
            "picjson": picjson ?? "",
            "sfid": _sfid ?? null,
            "shid": _shid ?? null,
            "title": _title ?? null,
            "sysmid": _mid ?? null,
            "removePicid": _deleteIds ?? null,
          };
          print("准备多图上传测试参数: ${paramsMap}");
          VgHttpUtils.post(url,
              params: paramsMap,
              callback: BaseCallback(onSuccess: (val) {
                VgHudUtils.hide(_context);
                callback?.onSuccess(list);
                VgEventBus.global.send(new RefreshSmartHomeCategoryEvent(id: _scid));
                VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
                VgEventBus.global.send(new RefreshSmartHomeFolderDetailEvent());
              }, onError: (msg) {
                VgHudUtils.hide(_context);
                callback?.onError(msg);
              }));
        }


      }).catchError((e) {
        VgHudUtils.hide(_context);
        callback?.onError("上传失败");
      });
  }

  ///多图上传
  void multiUpload(VgBaseCallback callback)async{
    if (_uploadList == null || _uploadList.isEmpty) {
      callback?.onError("需要上传的数据为空");
      return;
    }
    VgHudUtils.show(_context, "正在发布");
    try {
      for (SmartHomeUploadItemBean item in _uploadList) {
        item = await _manageFolder(item);
      }
    } catch (e) {
      callback?.onError("处理出现异常");
      print("上传报错:$e");
      return;
    }
    _uploadList.removeWhere((element) => element == null);
    List<Future<SmartHomeUploadItemBean>> futureList = List();
    for(int i = 0; i < _uploadList.length; i++){
      SmartHomeUploadItemBean item = _uploadList[i];
      item.sortIndex = i;
      futureList.add(_httpMultiFolder(item, onGetNewFileLength: (value){
        item.folderStorage = value;
      }));
    }
    Future.wait(futureList)
      ..then((List<SmartHomeUploadItemBean> list) {
        list.sort((left, right){
          return left.sortIndex.compareTo(right.sortIndex);
        });
        List<PicListItemBean> picList = new List();
        list.forEach((element) {
          PicListItemBean picListItemBean = new PicListItemBean(
            picurl: element.getPicUrl()??"",
            linkpic: element.linkCover??"",
            type: element.type??"",
            picname: element.folderName??"",
            picsize: element.getSize()??"",
            picstorage: element.getStorage()??"",
            videotime: element.videoDuration??0,
            videopic: element.videoNetCover??"",
            videoid: element.videoid??"",
            sd_video: element?.sdVideo??"",
            sd_storage: element?.getSDStorage()??"",
            scid: element.getScid()??(_scid??""),
            style: element.style??"99",
            backup: element.backup??"",
            picid: element.getPicid(),
          );
          picList.add(picListItemBean);
        });
        String picjson = "";
        if(picList.isNotEmpty){
          picjson = json.encode(picList);
        }
        //接口
        String url;
        Map<String, dynamic> paramsMap;
        if(StringUtils.isEmpty(_sfid)){
          url = NetApi.SMART_HOME_PUBLISH;
          paramsMap = {
            "authId": UserRepository.getInstance().authId ?? "",
            "backup": _desc ?? "",
            "coversize": picList.elementAt(_coverIndex)?.picsize ?? "",
            "coverurl": picList.elementAt(_coverIndex)?.getCoverUrl() ?? "",
            "scid": _scid ?? "",
            "title": _title ?? "",
            "shid": _shid ?? "",
            "picjson": picjson ?? "",
            "sysmid": _mid ?? "",
            "type": _type ?? "",
          };
          print("准备多图上传测试参数: ${paramsMap}");
          VgHttpUtils.post(url,
              params: paramsMap,
              callback: BaseCallback(onSuccess: (val) {
                VgHudUtils.hide(_context);
                callback?.onSuccess(list);
                VgEventBus.global.send(new RefreshSmartHomeCategoryEvent(id: _scid));
                VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
              }, onError: (msg) {
                VgHudUtils.hide(_context);
                callback?.onError(msg);
              }));
        }else{
          url = NetApi.SMART_HOME_EDIT_FOLDER;
          paramsMap = {
            "authId": UserRepository.getInstance().authId ?? "",
            "backup": _desc ?? "",
            "coversize": picList.elementAt(_coverIndex)?.picsize ?? "",
            "coverurl": picList.elementAt(_coverIndex)?.getCoverUrl() ?? "",
            "scid": _scid ?? "",
            "title": _title ?? "",
            "shid": _shid ?? "",
            "picjson": picjson ?? "",
            "sfid": _sfid ?? "",
            "sysmid": _mid ?? "",
            "type": _type ?? "",
          };
          print("准备多图上传测试参数: ${paramsMap}");
          VgHttpUtils.post(url,
              params: paramsMap,
              callback: BaseCallback(onSuccess: (val) {
                VgHudUtils.hide(_context);
                callback?.onSuccess(list);
                VgEventBus.global.send(new RefreshSmartHomeCategoryEvent(id: _scid));
                VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
                VgEventBus.global.send(new RefreshSmartHomeFolderDetailEvent());
              }, onError: (msg) {
                VgHudUtils.hide(_context);
                callback?.onError(msg);
              }));
        }


      }).catchError((e) {
        VgHudUtils.hide(_context);
        callback?.onError("上传失败");
      });

  }


  ///处理文件
  Future<SmartHomeUploadItemBean> _manageFolder(
      SmartHomeUploadItemBean item) async {
    if (item == null ||
        item.type == null ||
        StringUtils.isEmpty(item.localUrl)) {
      return null;
    }
    if (item.isImage()) {
      return _decodeImage(item);
    }
    if (item.is3DLink()) {
      return _decode3DLink(item);
    }
    if (item.isVideo()) {
      return await _decodeVideo(item);
    }
    return null;
  }

  SmartHomeUploadItemBean _decodeImage(SmartHomeUploadItemBean item) {
    if (item == null ||
        item.type == null ||
        StringUtils.isEmpty(item.localUrl)) {
      return null;
    }

    File file = File(item.localUrl);
    item.folderStorage = file.lengthSync();

    FileImage image = FileImage(File(item.localUrl));
    if(item.folderWidth == null || item.folderHeight == null){
      // 预先获取图片信息
      image
          .resolve(new ImageConfiguration())
          .addListener(new ImageStreamListener((ImageInfo info, bool _) {
        item.folderWidth = info.image.width;
        item.folderHeight = info.image.height;
        return item;
      }));
    }else{
      return item;
    }

  }

  Future<SmartHomeUploadItemBean> _decodeVideo(
      SmartHomeUploadItemBean item) async {
    if (item == null ||
        item.type == null ||
        StringUtils.isEmpty(item.localUrl)) {
      return null;
    }
    File file = File(item.localUrl);
    if(StringUtils.isEmpty(item.videoLocalCover)){
      Directory rootPath = await getTemporaryDirectory();
      Directory tempDirectory = new Directory('${rootPath.path}/imageTemp');
      if (!tempDirectory.existsSync()) {
        tempDirectory.createSync();
      }
      String tmpVideoCover = await VideoThumbnail.thumbnailFile(
        video: item.localUrl,
        thumbnailPath: tempDirectory?.path,
        imageFormat: ImageFormat.JPEG,
        maxWidth: 1920,
        quality: 100,
      );
      item.videoLocalCover = tmpVideoCover;
    }
    //
    VideoPlayerController videoController = VideoPlayerController.file(file);
    await videoController.initialize();
    item.videoDuration = videoController?.value?.duration?.inSeconds;
    item.folderWidth = videoController?.value?.size?.width?.floor();
    item.folderHeight = videoController?.value?.size?.height?.floor();
    item.folderStorage = file.lengthSync();
    videoController.dispose();
    return item;
  }

  SmartHomeUploadItemBean _decode3DLink(SmartHomeUploadItemBean item) {
    if (item == null ||
        item.type == null ||
        StringUtils.isEmpty(item.localUrl)) {
      return null;
    }

    File file = File(item.localUrl);
    item.folderStorage = file.lengthSync();

    FileImage image = FileImage(File(item.localUrl));
    if(item.folderWidth == null || item.folderHeight == null){
      // 预先获取图片信息
      image
          .resolve(new ImageConfiguration())
          .addListener(new ImageStreamListener((ImageInfo info, bool _) {
        item.folderWidth = info.image.width;
        item.folderHeight = info.image.height;
        return item;
      }));
    }else{
      return item;
    }

  }


  //多图上传
  Future<SmartHomeUploadItemBean> _httpMultiFolder(
      SmartHomeUploadItemBean item, {ValueChanged<int> onGetNewFileLength}) async {
    if (item == null) {
      return null;
    }
    if (item.isImage() || item.is3DLink()) {
      if(StringUtils.isNotEmpty(item.netUrl)){
        return item;
      }
      try {
        if(item.isImage()){
          item.netUrl = await VgMatisseUploadUtils.uploadSingleImageForFuture(
              item.localUrl,
              isNoCompress: true,
              onGetNewFileLength: onGetNewFileLength
          );
        }else{
          item.linkCover = await VgMatisseUploadUtils.uploadSingleImageForFuture(
              item.localUrl,
              isNoCompress: true,
              onGetNewFileLength: onGetNewFileLength
          );
        }

        if(StringUtils.isEmpty(item.folderName)){
          item.folderName=item?.getFolderNameStr() ?? "";
        }
        return item;
      } catch (e) {
        print("上传单图异常：$e");
      }
    }

    if (item.isVideo()) {
      if(StringUtils.isNotEmpty(item.netUrl)){
        if(StringUtils.isEmpty(item.videoLocalCover) && StringUtils.isNotEmpty(item.videoNetCover)){
          //视频跟封面地址都已上传
          return item;
        }else{
          //单独上传封面
          item.videoNetCover =
          await VgMatisseUploadUtils.uploadSingleImageForFuture(
              item.videoLocalCover,
              isNoCompress: true);
          return item;
        }
      }else{
        try {
          VideoUploadSuccessBean successBean =
          await VgMatisseUploadUtils.uploadSingleVideoForFuture(
              item.localUrl);
          item.netUrl = successBean.url;
          item.videoid = successBean.videoid;
          item.folderName = VgMatisseUploadUtils.getVideoPath();
          if (!StringUtils.isEmpty(successBean.fileSize)) {
            item.folderStorage = int.parse(successBean.fileSize);
          }
          item.sdVideo = successBean.sdVideo;
          item.sdStorage = successBean.getHdStorage();
          // if (StringUtils.isEmpty(successBean.coverUrl)) {
          item.videoNetCover =
          await VgMatisseUploadUtils.uploadSingleImageForFuture(
              item.videoLocalCover,
              isNoCompress: true);
          // } else {
          //   item.videoNetCover = successBean.coverUrl;
          // }
          return item;
        } catch (e) {
          print("MediaLibraryIndexService上传异常：$e");
        }
      }
    }
    return null;
  }
}
